package com.study.lxy.netty.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 简单的服务器实现类
 * 通过线程池控制并发
 */
public class SimpleServerWiithThreadPool {
    public static void main(String[] args) throws IOException {
        int port = 8080;
        ServerSocket serverSocket = null;
        try {
            ExecutorService executorService = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
                    20,
                    120L,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(1000));
            serverSocket = new ServerSocket(8080);
            while (true){
                Socket clientSocket = serverSocket.accept();
                executorService.execute(new ServerSocketHandler(clientSocket));
            }
        } finally {
            if(serverSocket != null){
                serverSocket.close();
            }
        }
    }
}
